package com.ruoyi.wx.controller;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.wx.service.WxService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description: TODO
 * @Create by: jacob
 * @Date: 2025/7/20
 * 遇见未来的自己
 */
@Controller
@RequestMapping("payer")
public class PayerController extends BaseController {

    @Autowired
    private WxService wxService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private SysLoginService loginService;


    //code=CODE&state=STATE
    @Anonymous
    @GetMapping("/wxlogin")
    public void wxlogin(@RequestParam("code") String code, @RequestParam("state") String state, HttpServletResponse response) throws IOException {
        if (StringUtils.isBlank(state)) {
            throw new RuntimeException("缺少必要参数");
        }
        String redirectUrl = state;

        JSONObject json = wxService.getLoginAccessToken(code);
        String access_token = json.getString("access_token");
        String openid = json.getString("openid");

        JSONObject jsonObject = wxService.getLoginUserInfo(access_token, openid);
        String nickname = jsonObject.getString("nickname");// 昵称
        String sex = jsonObject.getString("sex");// 性别 0-男 1-女
        String headimgurl = jsonObject.getString("headimgurl");// 头像

        // 通过openid查找用户，不存在则保存，存在更新昵称和头像
        sysUserService.saveOrUpdateUserInfo( openid, nickname, sex, headimgurl);

        // 生成令牌
        String token = loginService.wxlogin(openid);
        response.sendRedirect(redirectUrl + "#/pages/shoukuanma/shoukuanma?openid=" + openid + "&token=" + token);
    }
}
